import { User } from '../../models/user'
import jwt from 'jsonwebtoken'
import bcrypt from 'bcryptjs'
import { connectToDatabase } from '../../db/mongo'
import nodemailer from 'nodemailer'

export default defineEventHandler(async (event) => {
  const body = await readBody(event)
  
  // 输入验证
  if (!body.email || !body.password) {
    throw createError({
      statusCode: 400,
      statusMessage: 'EMAIL_PASSWORD_REQUIRED'
    })
  }

  await connectToDatabase()
  
  // 检查邮箱是否已注册
  const existingUser = await User.findOne({ email: body.email })
  if (existingUser) {
    throw createError({
      statusCode: 409,
      statusMessage: 'EMAIL_EXISTS'
    })
  }

  // 密码哈希处理
  const salt = await bcrypt.genSalt(10)
  const passwordHash = await bcrypt.hash(body.password, salt)

  // 创建新用户
  const newUser = new User({
    email: body.email,
    passwordHash,
    emailVerified: false
  })

  await newUser.save()

  // 生成验证令牌
  const verifyToken = jwt.sign(
    { userId: newUser._id },
    useRuntimeConfig().jwtSecret,
    { expiresIn: '1h' }
  )

  // 发送验证邮件
  const transporter = nodemailer.createTransport({
    host: useRuntimeConfig().smtpConfig.host,
    port: useRuntimeConfig().smtpConfig.port,
    auth: {
      user: useRuntimeConfig().smtpConfig.user,
      pass: useRuntimeConfig().smtpConfig.pass
    }
  })

  await transporter.sendMail({
    from: 'noreply@example.com',
    to: body.email,
    subject: 'Email Verification',
    html: `请点击链接验证邮箱：<a href="${useRuntimeConfig().public.siteUrl}/auth/verify?token=${verifyToken}">验证邮箱</a>`
  })

  return {
    status: 'success',
    message: 'REGISTRATION_SUCCESS'
  }
})